package com.mobimagic.lockscreen.activity;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.mobimagic.lockscreen.MobileChargingHelper;
import com.mobimagic.lockscreen.R;
import com.mobimagic.lockscreen.remaintime.MobileChargingService;
import com.mobimagic.lockscreen.remaintime.StaticHandler;
import com.mobimagic.lockscreen.remaintime.aidl.ChargingServiceAidl;
import com.mobimagic.lockscreen.remaintime.aidl.RemaintTimeWatcher;
import com.mobimagic.lockscreen.report.StatKey;
import com.mobimagic.lockscreen.report.Statistician2;
import com.mobimagic.lockscreen.sdk.ILockScreenBooster;
import com.mobimagic.lockscreen.sdk.LockScreenSDK;
import com.mobimagic.lockscreen.view.DateView;
import com.mobimagic.lockscreen.view.LayoutData;
import com.mobimagic.lockscreen.view.MobileChargingView;
import com.mobimagic.lockscreen.view.MobileChargingView.OnChargingViewSlideListener;
import com.qihoo360.mobilesafe.telephonyInterface.DualPhoneStateListener;
import com.qihoo360.mobilesafe.telephonyInterface.OperatorInterface;

public class MobileChargingActivity extends BaseActivity implements StaticHandler.MessageHandler, View.OnClickListener {
    private static final String TAG = "MobileChargingActivity";

    public static final String EXTRA_FROM = "from";
    public static final int EXTRA_FROM_CLICK_TRIP_BTN = 0;
    public static final int EXTRA_FROM_CONNECT = 1;
    public static final int EXTRA_FROM_DISCONNECT = 2;
    public static final int EXTRA_FROM_SCREENOFF = 3;
    public static final int EXTRA_FROM_SCREENON = 4;
    public static final int EXTRA_FROM_OTHER_CHARGING_APP_SCREEN_OFF = 5;
    public static final int EXTRA_FROM_OTHER_CHARGING_APP_SCREEN_ON = 6;
    public static final int EXTRA_FROM_BOOST_CARD = 7;
    public static final int EXTRA_FROM_ONLY_REFRESH = 8;
    public static final int EXTRA_FROM_CHECK_ALARM_SCREEN_ON = 9;
    private Context mContext;
    private BroadcastReceiver mTimeTickReceiver;
    private DateView mDateView;
    private ILockScreenBooster mLockScreenBooster;
    private MobileChargingView mMobileChargingView;
    private BroadcastReceiver broadcastReceiver;
    private PowerManager mPowerManager;
    private boolean hasStop = false;
    private ChargingServiceAidl chargingServiceAidl;
    private ServiceConnection connection;
    private RemaintTimeWatcher remaintTimeWatcher;
    private DualPhoneStateListener mCallPhoneStateListener;
    private MobileChargingView.ActivityStatus mActivityStatus;
    private Handler handler;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:SS");
    private int mFrom;
    private MobileChargingHelper mMobileChargingHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mMobileChargingHelper = MobileChargingHelper.getInstance();
        mLockScreenBooster = LockScreenSDK.getInstance().getLockScreenBooster();
        mActivityStatus = MobileChargingView.ActivityStatus.Create;
        super.onCreate(savedInstanceState);
        mMobileChargingHelper.setChargingActivity(this);
        mFrom = getIntent().getIntExtra(EXTRA_FROM, EXTRA_FROM_CONNECT);
        if (DEBUG) {
            Log.i(TAG, "onCreate==mFrom" + mFrom);
        }

        handler = new StaticHandler(this, Looper.myLooper());
        mMobileChargingHelper.getColorHelper().change(mFrom, true);
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //2.2的手机全屏加通明activity有问题
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow()
                    .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        LayoutData.create(this);
        mContext = LockScreenSDK.getInstance().getContext();
        initBooster();
        //        EventBus.getDefault().register(this);
        setContentView(R.layout.mobile_charging_view);
        mDateView = (DateView) findViewById(R.id.date_view);
        registerTimeReceiver();
        registerBatteryReceiver();
        initUI();
        remaintTimeWatcher = new RemaintTimeWatcher.Stub() {

            @Override
            public void onRemaintTimeChanged(int remaind) throws RemoteException {
                mMobileChargingHelper.charge.setServiceRemaind(remaind);
            }
        };
        mMobileChargingView.setOnChargingViewSlideListener(new OnChargingViewSlideListener() {

            @Override
            public void OnChargingViewSlideFinished() {
                finish();
            }
        });
        mMobileChargingView.onActivityCreate(mPowerManager.isScreenOn(), mFrom);
        connection = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                chargingServiceAidl = ChargingServiceAidl.Stub.asInterface(service);
                try {
                    chargingServiceAidl.register(remaintTimeWatcher);
                    mMobileChargingHelper.charge.setServiceRemaind(chargingServiceAidl.getRemaintTime());
                } catch (RemoteException e) {
                    if (DEBUG) {
                        Log.e(TAG, "remote error", e);

                    }
                }

            }
        };
        Intent intent = new Intent(this, MobileChargingService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

        registCallIn();
        if (mFrom == EXTRA_FROM_SCREENOFF && !mPowerManager.isScreenOn()) {
            mMobileChargingHelper.onShowButScreenOff();
        }
        logBottomApp(mFrom);
    }

    @Override
    public void handleMessage(Message msg) {

    }

    private void logBottomApp(int from) {
        String second = mMobileChargingHelper.getTop5AppName();
        String time = simpleDateFormat.format(new Date());
        Statistician2.dbLog(StatKey.STATISTIC_MOBILE_CHARGING_BOTTOMAPP, String.valueOf(from), time, second);
    }

    private void registCallIn() {
        mCallPhoneStateListener = new DualPhoneStateListener() {

            @Override
            public void onCallStateChanged(int state, String incomingNumber, int card) {

                switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    if (DEBUG) {
                        Log.i(TAG, "incoming call mActivityStatus=" + mActivityStatus);
                    }
                    if (mActivityStatus == MobileChargingView.ActivityStatus.Resume) {
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (DEBUG) {
                                    Log.i(TAG, "incoming call.run() mActivityStatus=" + mActivityStatus);
                                }
                                if (mActivityStatus == MobileChargingView.ActivityStatus.Resume) {
                                    Statistician2.dbLog(StatKey.STATISTIC_MOBILE_ACTIVITY_RESUME_CALLING);
                                    finish();
                                }
                            }
                        }, 2500);
                    }

                    break;

                case TelephonyManager.CALL_STATE_IDLE:
                    if (DEBUG) {
                        Log.i(TAG, "phone stat idle");
                    }

                    break;

                case TelephonyManager.CALL_STATE_OFFHOOK:
                    if (DEBUG) {
                        Log.i(TAG, "call state offhook");
                    }
                    break;
                default:
                    if (DEBUG) {
                        Log.i(TAG, "ignore phone stat: " + state);
                    }

                    break;
                }
            }

        };
        OperatorInterface.getDefault(LockScreenSDK.getInstance().getContext()).listen(mCallPhoneStateListener,
                DualPhoneStateListener.LISTEN_CALL_STATE);
    }

    private void unregistCallin() {
        if (mCallPhoneStateListener != null) {
            OperatorInterface.getDefault(LockScreenSDK.getInstance().getContext()).unListen(
                    DualPhoneStateListener.LISTEN_CALL_STATE);
            mCallPhoneStateListener = null;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mFrom = intent.getIntExtra(EXTRA_FROM, EXTRA_FROM_CONNECT);
        mMobileChargingView.onNewIntent(mPowerManager.isScreenOn(), mFrom);
        mDateView.updateCurrentDate();
        if (DEBUG) {
            Log.i(TAG, "onNewIntent==mFrom" + mFrom);
        }
        mMobileChargingHelper.getColorHelper().change(mFrom, hasStop);
        hasStop = false;
        if (mFrom == EXTRA_FROM_SCREENOFF && !mPowerManager.isScreenOn()) {
            mMobileChargingHelper.onShowButScreenOff();
        }
        logBottomApp(mFrom);
    }

    @Override
    protected void onStop() {
        super.onStop();
        hasStop = true;
        mMobileChargingView.onActivityStop();
        mActivityStatus = MobileChargingView.ActivityStatus.Stop;

    }

    @Override
    protected void onStart() {
        super.onStart();
        mMobileChargingView.onActivityStart();
        mActivityStatus = MobileChargingView.ActivityStatus.Start;
    }

    //    public void onEventMainThread(AdvEvent event) {
    //        mMobileChargingView.onEventMainThread(event);
    //    }

    private void registerBatteryReceiver() {
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                mMobileChargingView.onReceiver(intent);
            }
        };
        try {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
            intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
            intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
            intentFilter.addAction(Intent.ACTION_SCREEN_ON);
            intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
            registerReceiver(broadcastReceiver, intentFilter);
        } catch (Exception e) {
            if (DEBUG) {
                Log.e(TAG, " ChargingStateMonitor register fail ", e);
            }
            broadcastReceiver = null;
        }
    }

    private void initUI() {
        mMobileChargingView = (MobileChargingView) findViewById(R.id.mobile_charging_view);
    }

    private void initBooster() {
        mLockScreenBooster.startLoadBoost();
    }

    /**
     * 注册时间变化监听器
     */
    private void registerTimeReceiver() {
        mTimeTickReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context paramContext, Intent paramIntent) {
                if (paramIntent != null) {
                    if (DEBUG) {
                        Log.d(TAG, "onReceive action:" + paramIntent.getAction());
                    }
                    mDateView.updateCurrentDate();
                }
            }
        };
        mContext.registerReceiver(mTimeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));

    }

    protected void onResume() {
        super.onResume();
        mMobileChargingView.onActivityResume();
        mActivityStatus = MobileChargingView.ActivityStatus.Resume;
        mMobileChargingHelper.killOthers();
    }

    @Override
    protected void onPause() {
        super.onPause();
        String top = mMobileChargingHelper.getTopAppPackageName();
        if (!getPackageName().equals(top)) {
            String screenOn = mPowerManager.isScreenOn() ? "2" : "1";
            Statistician2.dbLog(StatKey.STATISTIC_MOBILE_CHARGING_NOT_SHOW, screenOn, top);
        }
        mActivityStatus = MobileChargingView.ActivityStatus.Pause;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mActivityStatus = MobileChargingView.ActivityStatus.Destory;
        if (mTimeTickReceiver != null) {
            mContext.unregisterReceiver(mTimeTickReceiver);
        }
        mLockScreenBooster.stopLoadBoost();
        if (mMobileChargingView != null) {
            mMobileChargingView.onActivityDestory();
        }
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
            broadcastReceiver = null;
        }
        //        EventBus.getDefault().unregister(this);
        unregistCallin();
        if (connection != null) {
            unbindService(connection);
        }

    }

    /**
     * gp广告xml布局文件里注册了click事件，但不用做任何响应
     * 
     * @param v
     */
    public void onClick(View v) {

        if (DEBUG) {
            Log.d(TAG, "onClick.");
        }
    }
}
